package com.itlaobing.binary;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/file/upload/single")
@MultipartConfig( location = "D:/upload")
public class FileUploadSingleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        throw new RuntimeException( "你居然敢用GET方式提交" );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType( "text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();

        // 通过 HttpServletRequest 实例 获得 HTTP请求 中的 实体数据
        Part p = request.getPart( "upfile" ); // 根据 form-data 的名称 获得指定的 form-data 对应的 Part 实例
        if( p != null ) {
            // Part 接口中的 getSubmittedFileName 是 Servlet 3.1 时提供的方法，而 Tomcat 7.0.X 仅支持 Servlet 3.0
            String filename = p.getSubmittedFileName(); // 获得用户上传的文件名称
            //System.out.println( "filename : " + filename );
            //System.out.println( "size : " + p.getSize() );
            if( filename != null && filename.length() > 0 ) {
                p.write(filename);
                out.println( "<h3>文件[ " + filename + " ]上传成功</h3>" );
            } else {
                out.println( "<h3>你丫没有选择文件就敢点上传</h3>" );
            }
        }
    }
}
